%%%-------------------------------------------------------------------
%%% @author admin
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 31. 十二月 2021 10:54
%%%-------------------------------------------------------------------
-module(net_lib).
-author("admin").

-include("log.hrl").
-include("system_pb.hrl").
-include("account.hrl").

%% API
-export([
    deal_pack/2,
    send/1
]).

deal_pack(PackList, undefined) ->
    deal_pack(PackList, init_users());
deal_pack([], Users) -> {ok, Users};
%%deal_pack([{MsgId, Info}| PackList], User) when MsgId div 1000 == 1 ->
%%  ?INFO("MsgId: ~w, Info: ~p", [MsgId, Info]),
%%  deal_pack(PackList, User);
deal_pack([{MsgId, Info}| PackList], User) when MsgId =< 1009 ->
    %% 1009以内是系统协议，无需角色进程启动
    case system_mHandler:handle_msg(Info, User) of
        {reply, ok, NUser} ->
            deal_pack(PackList, NUser);
        {reply, Return} ->
            send(Return),
            deal_pack(PackList, User);
        {noreply, NUser} ->
            deal_pack(PackList, NUser);
        {reply, Return, NUser} ->
            send(Return),
            deal_pack(PackList, NUser);
        {error, _} = Data ->
            Data;
        _ -> {error, bad_return}
    end;
deal_pack([Pack|PackList], Users = #users{account_pid = Pid, rec_count = RecCount}) ->
    case Pid =/= undefined andalso ((RecCount rem 5 =/= 0) orelse is_process_alive(Pid)) of
        true ->
            Pid ! {route_msg, Pack},
            deal_pack(PackList, Users#users{rec_count = RecCount + 1});
        _ ->
            {MsgId, Rec} = Pack,
            ?ERR("get message form python, msg_id:~w,  id:~w, data:~w",[MsgId, Rec#s2c_test.id, Rec#s2c_test.data]),
            {error, player_not_alive}
    end.

init_users() ->
    #users{}.


send(Msg) ->
    NetPid = erlang:get(net_pid),
    game_protocol:pack_send(NetPid, Msg).